package com.boat.hbase.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import org.apache.hadoop.hbase.client.Put;

/**
 * @Description: JavaBean转Put
 * @author boat
 * @date 2017年12月28日 下午4:45:28
 * @version V1.0
 */

public class BeanToPut {

	public static Put beanToPut(Object bean, byte[] rowKey, byte[] columnFamily) {
		Class type = bean.getClass();
		Put put = new Put(rowKey);
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(type);
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (int i = 0; i < propertyDescriptors.length; i++) {
				PropertyDescriptor descriptor = propertyDescriptors[i];
				String propertyName = descriptor.getName();
				if (!propertyName.equals("class")) {
					Method readMethod = descriptor.getReadMethod();
					Object value = readMethod.invoke(bean, new Object[0]);
					if (value != null) {
						put.addColumn(columnFamily, HBytesUtil.toBytesByString(propertyName), HBytesUtil.toBytes(value, value));
					}
				}
			}
			return put;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}
